package com.superzqb.asus.superzqbFragment.superzqbShopQrcode;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.superzqb.asus.superzqb.R;
import com.superzqb.asus.superzqbFragment.superzqbShopQrcode.image.GridviewAdapter;
import com.superzqb.asus.superzqbFragment.superzqbShopQrcode.image.ImageFloder;
import com.superzqb.asus.superzqbFragment.superzqbShopQrcode.image.ListviewAdapter;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

public class ChooseImg extends Activity {

	private ProgressDialog mProgressDialog;

	/**
	 * 存储文件夹中的图片数量
	 */
	private int item=0;
	/**
	 * 图片数量最多的文件夹
	 */
	private File mImgDir;
	/**
	 * 所有的图片
	 */
	private Boolean oneflag=true;//第一个文件夹
	private List<String> mImgs;

	private GridView mGirdView;
	/**
	 * 临时的辅助类，用于防止同一个文件夹的多次扫描
	 */
	private HashSet<String> mDirPaths = new HashSet<String>();

	/**
	 * 扫描拿到所有的图片文件夹
	 */
	private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();

	private RelativeLayout mBottomLy;

	private TextView mDirtext;
	private TextView mImageCount;
	private ImageButton mcelbutton,rightbutton;
	int totalCount = 0;

	private int mScreenHeight;
	private PopupWindow pop;
	private Myalbumlist albumlist;

	// private ListImageDirPopupWindow mListImageDirPopupWindow;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			mProgressDialog.dismiss();
			// 为View绑定数据
			data2View();
			// 初始化展示文件夹的popupWindw
			initListPopupWindw();
		}
	};

	private GridviewAdapter mAdapter;

	/**
	 * 为View绑定数据
	 */
	private void data2View() {
		if (mImgDir == null) {
			Toast.makeText(getApplicationContext(), "很抱歉，没有找到图片",
					Toast.LENGTH_SHORT).show();
			return;
		}

		mImgs = Arrays.asList(mImgDir.list());
		/**
		 * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
		 */
		mAdapter = new GridviewAdapter(getApplicationContext(), mImgs,
				R.layout.grid_item, mImgDir.getAbsolutePath());
		mGirdView.setAdapter(mAdapter);
		ImageFloder i=new ImageFloder();
		i.setDir(mImgDir.getAbsolutePath());
		mDirtext.setText(i.getName());
	};
	protected void initListPopupWindw() {
		// TODO Auto-generated method stub
		WindowManager wm=(WindowManager) getSystemService(Context.WINDOW_SERVICE);
		int wwidth=wm.getDefaultDisplay().getWidth(); //手机屏幕的宽度

		albumlist=new Myalbumlist(this);
		pop= albumlist.getMenu(getApplicationContext(),wwidth,mImageFloders,clickkeyListener, ClickListener);

		// 设置选择文件夹的回调

	}

	/**
	 * 初始化展示文件夹的popupWindw
	 */
	// private void initListDirPopupWindw()
	// {
	// mListImageDirPopupWindow = new ListImageDirPopupWindow(
	// LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
	// mImageFloders, LayoutInflater.from(getApplicationContext())
	// .inflate(R.layout.list_dir, null));
	//
	// mListImageDirPopupWindow.setOnDismissListener(new OnDismissListener()
	// {
	//
	// @Override
	// public void onDismiss()
	// {
	// // 设置背景颜色变暗
	// WindowManager.LayoutParams lp = getWindow().getAttributes();
	// lp.alpha = 1.0f;
	// getWindow().setAttributes(lp);
	// }
	// });
	// // 设置选择文件夹的回调
	// mListImageDirPopupWindow.setOnImageDirSelected(this);
	// }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.chooseimg);
		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		mScreenHeight = outMetrics.heightPixels;

		initView();
		getImages();
		// initEvent();


	}
	private Button.OnClickListener scan=new Button.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			if(v.getId()==R.id.dirButton){
				pop.showAtLocation(findViewById(R.id.imagelayout),Gravity.LEFT, 0, 0);
				//pop.showAsDropDown(findViewById(R.id.imagelayout),0,0);
			}else if(v.getId()==R.id.ceButton){
				finish();
			}

		}
	};

	private OnItemClickListener listener=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
								long arg3) {
			// TODO Auto-generated method stub

			Intent intent=new Intent();
			intent.putExtra("RESULT",mImgDir.getAbsolutePath()+"/"+mImgs.get(arg2));
			setResult(RESULT_OK, intent);
			finish();
		}

	};

	/**
	 * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描，最终获得jpg最多的那个文件夹
	 */
	private void getImages() {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
			return;
		}
		// 显示进度条
		mProgressDialog = ProgressDialog.show(this, null, "正在加载...");

		new Thread(new Runnable() {
			@Override
			public void run() {

				String firstImage = null;

				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = ChooseImg.this
						.getContentResolver();

				// 只查询jpeg和png的图片
				Cursor mCursor = mContentResolver.query(mImageUri, null,
						MediaStore.Images.Media.MIME_TYPE + "=? or "
								+ MediaStore.Images.Media.MIME_TYPE + "=?",
						new String[] { "image/jpeg", "image/png" },
						MediaStore.Images.Media.DATE_MODIFIED);


				while (mCursor.moveToNext()) {
					// 获取图片的路径
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATA));


					// 拿到第一张图片的路径
					if (firstImage == null)
						firstImage = path;
					// 获取该图片的父路径名
					File parentFile = new File(path).getParentFile();
					if (parentFile == null)
						continue;
					String dirPath = parentFile.getAbsolutePath();
					ImageFloder imageFloder = null;
					// 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
					if (mDirPaths.contains(dirPath)) {
						continue;
					} else {
						mDirPaths.add(dirPath);
						// 初始化imageFloder
						imageFloder = new ImageFloder();
						imageFloder.setDir(dirPath);
						imageFloder.setFirstImagePath(path);
						imageFloder.setFlag(true);
					}
					if(parentFile.list()==null)continue ;
					int picSize = parentFile.list(new FilenameFilter() {
						@Override
						public boolean accept(File dir, String filename) {
							if (filename.endsWith(".jpg")
									|| filename.endsWith(".png")
									|| filename.endsWith(".jpeg"))
								return true;
							return false;
						}
					}).length;
					totalCount += picSize;

					imageFloder.setCount(picSize);

					if(oneflag){
						oneflag=false;
						imageFloder.setFlag(true);
						mImgDir = parentFile;
					}else{
						imageFloder.setFlag(false);
					}
					mImageFloders.add(imageFloder);



				}
				mCursor.close();

				// 扫描完成，辅助的HashSet也就可以释放内存了
				mDirPaths = null;

				// 通知Handler扫描图片完成
				mHandler.sendEmptyMessage(0x110);

			}
		}).start();

	}

	/**
	 * 初始化View
	 */
	private void initView() {
		mGirdView = (GridView) findViewById(R.id.imagegridview);
		mDirtext = (TextView) findViewById(R.id.dirtext);
		mcelbutton=(ImageButton)findViewById(R.id.ceButton);
		rightbutton=(ImageButton)findViewById(R.id.dirButton);
		mcelbutton.setOnClickListener(scan);
		rightbutton.setOnClickListener(scan);
		mGirdView.setOnItemClickListener(listener);
	}

	// private void initEvent()
	// {
	// /**
	// * 为底部的布局设置点击事件，弹出popupWindow
	// */
	// mBottomLy.setOnClickListener(new OnClickListener()
	// {
	// @Override
	// public void onClick(View v)
	// {
	// mListImageDirPopupWindow
	// .setAnimationStyle(R.style.anim_popup_dir);
	// mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0, 0);
	//
	// // 设置背景颜色变暗
	// WindowManager.LayoutParams lp = getWindow().getAttributes();
	// lp.alpha = .3f;
	// getWindow().setAttributes(lp);
	// }
	// });
	// }
	//
	// @Override
	// public void selected(ImageFloder floder)
	// {
	//
	// mImgDir = new File(floder.getDir());
	// mImgs = Arrays.asList(mImgDir.list(new FilenameFilter()
	// {
	// @Override
	// public boolean accept(File dir, String filename)
	// {
	// if (filename.endsWith(".jpg") || filename.endsWith(".png")
	// || filename.endsWith(".jpeg"))
	// return true;
	// return false;
	// }
	// }));
	// /**
	// * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
	// */
	// mAdapter = new MyAdapter(getApplicationContext(), mImgs,
	// R.layout.grid_item, mImgDir.getAbsolutePath());
	// mGirdView.setAdapter(mAdapter);
	// // mAdapter.notifyDataSetChanged();
	// mImageCount.setText(floder.getCount() + "张");
	// mChooseDir.setText(floder.getName());
	// mListImageDirPopupWindow.dismiss();
	//
	// }
	private OnTouchListener touchListener = new OnTouchListener() {

		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
				pop.dismiss();
			}
			return false;
		}
	};
	private OnClickListener clickkeyListener = new OnClickListener() {



		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			pop.dismiss();
		}

	};
	View v=null;
	private OnItemClickListener ClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
								long arg3) {
			if (v != null) {
				v.setBackgroundColor(0);
			} else {
				v = ListviewAdapter.v.getChildAt(0);
				v.setBackgroundColor(0);
			}
			arg1.setBackgroundColor(Color.parseColor("#87CEFF"));
			v = arg1;
			System.out.println(arg1);
//			mImageFloders.get(item).setFlag(false);
//			mImageFloders.get(arg2).setFlag(true);
////			//Myalbumlist.listadapter = new ListviewAdapter(ImagecheckActivity.this, ListviewAdapter.mDatas);
////	        //alist.setAdapter(listadapter);
////			Myalbumlist.alist.setAdapter(new ListviewAdapter(ImagecheckActivity.this,mImageFloders));
//			item=arg2;
			//System.out.println(""+arg0);
			mImgDir = new File(mImageFloders.get(arg2).getDir());
			mImgs = Arrays.asList(mImgDir.list(new FilenameFilter()
			{
				@Override
				public boolean accept(File dir, String filename)
				{
					if (filename.endsWith(".jpg") || filename.endsWith(".png")
							|| filename.endsWith(".jpeg"))
						return true;
					return false;
				}
			}));
			mAdapter = new GridviewAdapter(getApplicationContext(), mImgs,
					R.layout.grid_item, mImgDir.getAbsolutePath());
			mGirdView.setAdapter(mAdapter);
			ImageFloder i=new ImageFloder();
			i.setDir(mImgDir.getAbsolutePath());
			mDirtext.setText(i.getName());
			//pop.dismiss();
		}
	};
}
